<template>
  <div class="page-mobile_area-agent">
    <div class="distribution_header">
      <div class="user">
        <img v-lazy="user_info.avatar" :key="user_info.avatar"/>
      </div>
      <div class="money_content">
        <span>
          <!-- <van-icon
            name="question-o"
            class="wenwen"
            @click="handleTips"
          /> -->
          未到账:</span>
        <span style="margin-right:5px;">￥{{ my_profile.padding || 0 }}</span>
        <span>可提现:</span>
        <span class="money" style="margin-right:5px;"
          >￥{{ my_profile.profit || 0 }}</span
        >
        <span>已提现:</span>
        <span>￥{{ my_profile.withdraw || 0 }}</span>
      </div>
      <div
        class="towithdrawal"
        @click="toPath('/m/withdrawal?type=area-agent')"
      >
        去提现
      </div>
      <!-- <div>{{user_info}}</div> -->
    </div>
    <div class="distribution_body">
      <van-tabs v-model="active" @change="handleTapChange" sticky>
        <van-tab name="profile" :title="'提现记录'">
          <div class="list-box" ref="profile">
            <div
              class="list-item"
              v-if="log_profile.length > 0"
              v-for="(item, index) in log_profile"
              :key="index"
            >
              <div class="item-left">
                <div class="item-name">代理分润提现￥{{ item.amount }}</div>
                <!-- <div class="item-subname">{{ item.acName || "未知" }}</div> -->
                <div class="item-content">
                  <div class="content-item">
                    昵称：{{ item.acName || "未知" }}
                  </div>
                  <div class="content-item">
                    申请时间：{{ trimDate(item.createTime) }}
                  </div>
                  <div class="content-item">
                    提现状态：<span
                      :class="[
                        item.status == 1
                          ? 'pending'
                          : item.status == 2
                          ? 'success'
                          : 'reject'
                      ]"
                      >{{
                        item.status == 1
                          ? "提现申请中"
                          : item.status == 2
                          ? "提现完成"
                          : "提现被驳回"
                      }}</span
                    >
                  </div>
                </div>
              </div>
              <div class="item-right">
                <span
                  :class="[
                    'item-currency',
                    item.status == 1 ? 'pending' : 'success'
                  ]"
                  >￥
                  <span class="item-cash">{{ item.amount }}</span>
                </span>
              </div>
            </div>
            <van-empty
              :description="'暂无提现记录哦~'"
              v-if="log_profile.length == 0"
            />
          </div>
        </van-tab>
        <van-tab name="log" :title="'代理利润记录'">
          <div class="list-box" ref="log">
            <div
              class="list-item"
              v-if="log_list.length > 0"
              v-for="(item, index) in log_list"
              :key="index"
            >
              <div class="item-left">
                <div class="item-name">{{ item.productInfo }}</div>
                <!-- <div class="item-subname">{{ item.acName || "未知" }}</div> -->
                <div class="item-content">
                  <div class="content-item">
                    昵称：{{ item.acName || "未知" }}
                  </div>
                  <div class="content-item">
                    支付时间：{{ trimDate(item.createTime) }}
                  </div>
                  <div class="content-item">
                    订单金额:￥{{ item.consumptionAmount }}
                  </div>
                </div>
              </div>
              <div class="item-right">
                <span class="item-currency"
                  >￥
                  <span class="item-cash">{{ item.profit }}</span>
                </span>
              </div>
            </div>
            <van-empty
              :description="'暂无代理利润记录哦~'"
              v-if="log_list.length == 0"
            />
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import {
  getAreaAgentLog,
  getOwnProfit,
  saveCashAdvance,
  getCashAdvance
} from "~/api/distribution";
export default {
  components: {},
  data() {
    return {
      page: 1,
      pageSize: 10,
      total: 0,
      log_page: 1,
      log_pageSize: 10,
      log_total: 0,
      log_list: [], //区域代理流水记录
      my_profile: {}, //我的收益
      log_profile: [], //提现记录
      active: "profile"
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      is_loading(state) {
        return state.is_loading;
      },
      token(state) {
        return state.token;
      }
    }),
    actived() {
      return this.$route.query.actived;
    }
  },
  watch: {},
  methods: {
    handleTips() {
      // this.$toast(7 + "天内获得的分销订单金额！");
    },
    handleTapChange(current) {
      this.$router.replace({
        path: "",
        query: {
          actived: current
        }
      });
    },
    toPath(path) {
      this.$router.push(path);
    },
    //获取下级分润记录
    async getAreaAgentLog(is_init) {
      let params = {
        sort: "createTime desc",
        offset: this.pageSize * (this.page - 1),
        limit: this.pageSize,
        agentId: this.user_info.id
      };
      let result = await getAreaAgentLog(params);
      console.log("下级分润记录:", result);
      if (result && result.data && result.data.code == 200) {
        this.total = result.data.data.total;
        if (is_init) {
          this.log_list = result.data.data.rows;
        } else {
          this.log_list = [...this.log_list, ...result.data.data.rows];
        }
      } else {
        this.$toast("获取失败！");
      }
    },
    //获取我的收益
    async getOwnProfit() {
      let result = await getOwnProfit({ userId: this.user_info.id });
      console.log("获取我的收益:", result);
      if (result && result.data && result.data.code == 200) {
        const { rows } = result.data.data;
        if (rows.length > 0) {
          this.my_profile = rows[0];
        }
      } else {
        this.$toast("获取失败！");
      }
    },
    //获取提现记录
    async getCashAdvance(is_init) {
      let params = {
        sort: "createTime desc",
        userId: this.user_info.id,
        offset: this.log_pageSize * (this.log_page - 1),
        limit: this.log_pageSize
      };
      let result = await getCashAdvance(params);
      console.log("获取提现记录:", result);
      if (result && result.data && result.data.code == 200) {
        const { rows, total } = result.data.data;
        this.log_total = total;
        if (is_init) {
          this.log_profile = rows;
        } else {
          this.log_profile = [...this.log_profile, ...rows];
        }
      } else {
        this.$toast("获取失败！");
      }
    },
    pullUp() {
      // 滚动条离顶部的距离
      let scrollTop = document.querySelector(".van-tabs__content").scrollTop;
      // 窗口可视区域高度
      let clientHeight = document.querySelector(".van-tabs__content")
        .offsetHeight;
      // 滚动区域高度
      let scrollHeight = document.querySelector(".van-tabs__content")
        .scrollHeight;
      // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      //   console.log(
      //     "scrollTop:" +
      //       scrollTop +
      //       "--" +
      //       "clientHeight:" +
      //       clientHeight +
      //       "--" +
      //       "scrollHeight:" +
      //       scrollHeight
      //   );
      if (scrollTop + clientHeight >= scrollHeight) {
        console.log("上拉加载");
        if (this.is_loading) {
          return;
        }
        if (this.active == "profile") {
          if (this.log_total <= this.log_profile.length) {
            return;
          }
          this.log_page++;
          this.getCashAdvance();
        } else if (this.active == "log") {
          if (this.total <= this.log_list.length) {
            return;
          }
          this.page++;
          this.getAreaAgentLog();
        }
      }
    },
    initPage() {
      if (!this.token || Object.keys(this.user_info).length == 0) {
        return this.$router.replace("/m/login");
      }
      if (this.actived && ["profile", "log"].includes(this.actived)) {
        this.active = this.actived;
      }
      this.getAreaAgentLog(true);
      this.getOwnProfit();
      this.getCashAdvance(true);
    },
    trimDate(date) {
      if (date) {
        let _date = new Date(date);
        return `${_date.getFullYear()}-${_date.getMonth() +
          1}-${_date.getDate()}  ${_date.getHours()}:${_date.getMinutes()}:${_date.getSeconds()}`;
      } else {
        return this.$t("locale.components.mobile.GroupChat.t7");
      }
    }
  },
  created() {
    this.initPage();
  },
  mounted() {
    if (process.client) {
      this.$nextTick(() => {
        document.querySelector(".van-tabs__content") &&
          document
            .querySelector(".van-tabs__content")
            .addEventListener("scroll", this.pullUp, false);
      });
    }
  },
  activated() {
    this.initPage();
    if (process.client) {
      this.$nextTick(() => {
        document.querySelector(".van-tabs__content") &&
          document
            .querySelector(".van-tabs__content")
            .addEventListener("scroll", this.pullUp, false);
      });
    }
  },
  deactivated() {
    if (process.client) {
      document.querySelector(".van-tabs__content") &&
        document
          .querySelector(".van-tabs__content")
          .removeEventListener("scroll", this.pullUp);
    }
  },
  destroyed() {
    if (process.client) {
      document.querySelector(".van-tabs__content") &&
        document
          .querySelector(".van-tabs__content")
          .removeEventListener("scroll", this.pullUp);
    }
  }
};
</script>

<style lang="scss" scoped>
.page-mobile_area-agent {
  .distribution_header {
    .user {
      width: 70px;
      height: 70px;
      overflow: hidden;
      border-radius: 50%;
      // box-sizing: border-box;
      margin: 30px auto 0;
      background-color: var(--theme-color);
      // img{
      //     width: 100%;
      //     height: 100%;
      //     display: block;
      // }
    }
    .money_content {
      text-align: center;
      font-family: SourceHanSansSC;
      font-weight: 700;
      // font-size: 26px;
      font-size: 12px;
      font-style: normal;
      letter-spacing: 0px;
      line-height: 50px;
      .wenwen {
        position: relative;
        left: 0;
        top: 1px;
      }
      .money {
        color: rgb(240, 40, 35);
      }
    }
    .towithdrawal {
      width: 100px;
      height: 30px;
      text-align: center;
      line-height: 30px;
      color: #ffffff;
      background-color: var(--theme-color);
      border-radius: 5px;
      margin: 0 auto 20px;
    }
  }
}
</style>
<style lang="scss">
.page-mobile_area-agent {
  .distribution_body {
    .van-tabs__content {
      height: calc(100vh - 244px - 0.8rem);
      overflow: auto;
      .van-tab__pane {
        width: 100%;
        height: 100%;
        .list-box {
          width: 100%;
          height: 100%;
          .list-item {
            display: flex;
            padding: 0.2rem 0.3rem;
            border-bottom: 0.02rem solid #ededf1;
            .item-left {
              width: 5.1rem;
              .item-name {
                font-size: 0.28rem;
                color: #4a4b4d;
              }
              .item-subname {
                margin-top: 0.1rem;
                font-size: 0.26rem;
                color: #727475;
              }
              .item-content {
                margin-top: 0.2rem;
                .content-item {
                  font-size: 0.24rem;
                  color: #adb0b3;
                }
                .content-item + .content-item {
                  margin-top: 0.2rem;
                }
              }
            }
            .item-right {
              flex: 1;
              display: flex;
              justify-content: center;
              align-items: center;
              .item-currency {
                font-size: 0.24rem;
                color: #4a4b4d;
                vertical-align: text-bottom;
                .item-cash {
                  font-size: 0.34rem;
                  color: #4a4b4d;
                }
              }
            }
            .pending {
              color: #e6a23c;
              .item-cash {
                color: #e6a23c;
              }
            }
            .success {
              color: #67c23a;
              .item-cash {
                color: #67c23a;
              }
            }
            .reject {
              color: #f56c6c;
              .item-cash {
                color: #f56c6c;
              }
            }
          }
        }
      }
    }
  }
}
</style>
